<template>
  <div class="home">
    <a-form
      :model="formState"
      name="basic"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="Username"
        name="username"
        :rules="[{ required: true, message: 'Please input your username!' }]"
      >
        <a-input v-model:value="formState.username" />
      </a-form-item>

      <a-form-item
        label="Password"
        name="password"
        :rules="[{ required: true, message: 'Please input your password!' }]"
      >
        <a-input-password v-model:value="formState.password" />
      </a-form-item>

      <a-form-item name="remember" :wrapper-col="{ offset: 8, span: 16 }">
        <a-checkbox v-model:checked="formState.remember">记住密码</a-checkbox>
      </a-form-item>

      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-button type="primary" html-type="submit" @click="change"
          >登录</a-button
        >
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import cache from "../cache/cache";
import { useRouter } from "vue-router";

const router = useRouter();
const formState = reactive({
  username: cache.getCache("name") ?? "",
  password: cache.getCache("password") ?? "",
  remember: true,
});
const onFinish = async (values) => {
  console.log("Success:", values);
  if (formState.remember) {
    cache.setCache("name", formState.username);
    cache.setCache("password", formState.password);

    var myHeaders = new Headers();
    myHeaders.append("Content-type", "application/json");
    myHeaders.append(
      "Cookie",
      `info={"username":"${values.username}","password":"${values.password}"}; info.sig=5vAzLGS4CjjtbKwR7dfTfx3jfBmfh3B3CzMf9JG5dWk`
    );

    var raw = JSON.stringify({
      username: values.username,
      password: values.password,
    });

    var requestOptions = {
      method: "POST",
      headers: myHeaders,
      body: raw,
      redirect: "follow",
    };
    fetch("/api/user/login", requestOptions)
      .then((response) => response.text())
      .then((result) => {
        if (JSON.parse(result).success) {
          router.push("/about");
        }
      })
      .catch(() => alert("账号或密码错误"));
  }
};

const onFinishFailed = (errorInfo) => {
  console.log("Failed:", errorInfo);
};
const change = () => {};
</script>
<style lang="less" scoped>
.home {
  display: flex;
  justify-content: center;
}
</style>
